<?php
class CategoriesController extends AppController {

	var $name = 'Categories';
	var $uses = array('Category');
	var $helpers = array('TreeView', 'Tree');
	
	var $paginate = array(
		'Category' => array(
	        'limit' => 10,
	        'order' => array(
	            'Category.id' => 'DESC'
	        )
		)
    );
	
	/**
	 * Category Model
	 *
	 * @var Category
	 */
	var $Category;
	
	/**
	 * Tyk zadavame spisaka na action-ite s publichen dostyp (action-ite bez authorizaciq)
	 */
	function __initPublicActions() {
		$this->Auth->allow(array(
			'init_db'
		));
	}
	
	function beforeFilter() {
        parent::beforeFilter();
        
        $this->__initPublicActions();
    }
    
    function init_db() {
    	$this->loadModel('Group');
    	
    	$group =& $this->Group;
    	
    	//------------- root [id=1]
    	$group->id = 1;
    	
    	$this->Acl->allow($group, 'controllers');
    	//------------/ root [id=1]
    	
    	//------------- user [id=2]
    	$group->id = 2;
    	
    	
    	//------------/ user [id=2]
    	
    	echo "all done";
    	exit;
    }
	
	function admin_index() {
		$this->Category->recursive = 0;
		$categories = $this->paginate('Category');
		
		for($i = 0, $categoriesSize = count($categories); $i < $categoriesSize; $i++) {
			$categoryParents = $this->Category->getpath($categories[$i]["Category"]["id"]);
			$categories[$i]["Category"]["parents"] = $categoryParents;
		}
		
		$this->set('categories', $categories);
	}

	function admin_add() {
		$this->Category->set($this->data);
		$this->Category->setValidation('admin_add');
		$fields_to_save = array(
			'lft', 'rght', 'parent_id', 'url_title', 'name', 'page_title', 'body'
		);
		
		if (!empty($this->data)) {
			$this->data["Category"] = $this->__trimData($this->data["Category"]);
			if($this->Category->validates()) {
				$this->data["Category"]["url_title"] = Inflector::slug(mb_strtolower($this->data["Category"]["name"], "UTF-8"), "-");
				
				if(empty($this->data["Category"]["parent_id"])) {
					$this->data["Category"]["parent_id"] = 0;
				}
				
				$this->Category->create();
				if ($this->Category->save($this->data, true, $fields_to_save)) {
					$this->Session->setFlash('Категорията е запаметена успешно');
					$this->redirect(array('admin' => true, 'plugin' => null, 'controller' => 'categories', 'action' => 'index'));
				} else {
					$this->Session->setFlash('Грешка: The Category could not be saved. Please, try again.');
				}
			} else {
				$this->Session->setFlash('Грешка');
			}
		}
		
		$this->set('categories', $this->Category->generateTreeList(null, null, null, '-', null));
		$this->set('nextAutoIncrement', $this->Category->getNextAutoIncrement());
	}

	function admin_edit($id = null) {
		$this->Category->idFieldValue = $id;
		$this->Category->set($this->data);
		$this->Category->setValidation('admin_edit');
		$fields_to_save = array(
			'lft', 'rght', 'parent_id', 'is_active', 'url_title', 'name', 'page_title', 'body'
		);
		
		if (!$id && empty($this->data)) {
			$this->Session->setFlash('Невалидна категория');
			$this->redirect(array('admin' => true, 'plugin' => null, 'controller' => 'categories', 'action' => 'index'));
		}
		if (!empty($this->data)) {
			$this->data["Category"] = $this->__trimData($this->data["Category"]);
			
			if($this->Category->validates()) {
				$this->data["Category"]["url_title"] = Inflector::slug(mb_strtolower($this->data["Category"]["name"], "UTF-8"), "-");
				
				if(empty($this->data["Category"]["parent_id"])) {
					$this->data["Category"]["parent_id"] = 0;
				}
				
				if ($this->Category->save($this->data, true, $fields_to_save)) {
					$this->Session->setFlash('Категорията е запаметена успешно');
					$this->redirect(array('admin' => true, 'plugin' => null, 'controller' => 'categories', 'action' => 'index'));
				} else {
					$this->Session->setFlash('Грешка: The Category could not be saved. Please, try again.');
				}
			} else {
				$this->Session->setFlash('Грешка');
			}
		}
		if (empty($this->data)) {
			$this->data = $this->Category->read(null, $id);
		}
		
		$this->set('categories', $this->Category->generateTreeList(array(
			'Category.id != ' => $id
		), null, null, '-', null));
	}

	function admin_delete($id = null, $confirm = false) {
		if (!$id) {
			$this->Session->setFlash('Невалидна категория');
			$this->redirect(array('admin' => true, 'plugin' => null, 'controller' => 'categories', 'action' => 'index'));
		}
		
		$category = $this->Category->read(null, $id);
		$this->set('category', $category);
		
		if($confirm) {
			if ($this->Category->delete($id)) {
				$this->Session->setFlash('Категорията е изтрита успешно');
				$this->redirect(array('admin' => true, 'plugin' => null, 'controller' => 'categories', 'action' => 'index'));
			}
			
			$this->Session->setFlash('Грешка: The Category could not be deleted. Please, try again.');
			$this->redirect(array('admin' => true, 'plugin' => null, 'controller' => 'categories', 'action' => 'index'));
		}
	}
	
	function admin_addall() {
		$this->Category->setValidation('admin_addall');
		
		$isError = false;
		$savedCategories = array();
		
		if (!empty($this->data)) {
			$this->data["Category"] = $this->__trimData($this->data["Category"]);
			$allCategoriesString = trim($this->data["Category"]["name"], " ,\t\n\r\0\x0B");

			if(!empty($allCategoriesString)) {
				$parent_id = $this->data["Category"]["parent_id"];
				if(empty($parent_id)) {
					$parent_id = 0;
				}
					
				unset($this->data["Category"]);
					
				$allCategoriesExploded = explode(",", $allCategoriesString);
					
				foreach ($allCategoriesExploded as $currentCategoryName) {
					$currentCategoryName = trim($currentCategoryName, " ,\t\n\r\0\x0B");
					if($currentCategoryName != "") {
						$this->data["Category"]["name"] = $currentCategoryName;
						$this->data["Category"]["parent_id"] = $parent_id;
						$this->data["Category"]["body"] = "";
						$this->data["Category"]["url_title"] = Inflector::slug(mb_strtolower($currentCategoryName, "UTF-8"), "-");
						
						$this->Category->set($this->data);
						
						if($this->Category->validates()) {
							$this->Category->create();
							if(!$this->Category->save($this->data)) {
								$isError = true;
								$this->Session->setFlash('Грешка: The Category could not be saved. Please, try again.');
								break;
							} else {
								$savedCategories[] = $currentCategoryName;
							}
						} else {
							$isError = true;
							$this->Session->setFlash('Грешка');
							break;
						}
					}
				}
					
				if(!$isError) {
					$this->Session->setFlash('Категориите са запаметени успешно');
					$this->redirect(array('admin' => true, 'plugin' => null, 'controller' => 'categories', 'action' => 'index'));
				}
			}
		}
		
		$this->set('isError', $isError);
		$this->set('savedCategories', $savedCategories);
		$this->set('categories', $this->Category->generateTreeList(null, null, null, '-', null));
	}
	
	// ---------------------------------------------------------------------------------------------
	
	function admin_tree_view_manager() {
		$this->set('categories', $this->Category->generateTreeList());
	}

	function admin_save() {
		// First get the tree in it's original format.
		$tree = $this->Category->generateTreeList();

		// Save string looks like ID-PARENTID,ID-PARENTID,....
		$save_string = $this->params['url']['save_string'];

		$associations = explode(',', $save_string);
		foreach ($associations as $relationship) {
			$ids = explode('-', $relationship);
			$saved_ids[] = $ids[0];

			$this_node_id = $ids[0];
			$this_node_parent_id = $ids[1];

			$this->Category->recursive = -1;
			$category = $this->Category->find('first', array('conditions' => array(
                    'Category.id' => $this_node_id,
			)
			));
			$this->Category->set($category);
			if (isset($category['Category']['id']) && $category['Category']['parent_id'] !== $this_node_parent_id) {
				//$ret = $this->Category->setParent($this_node_parent_id);
				$ret = $this->Category->saveField('parent_id', $this_node_parent_id);
				if ($ret === false) {
					$this->Session->setFlash('Failed to save the organizational chart.');
					$this->redirect(array('admin' => true, 'plugin' => null, 'controller' => 'categories', 'action'=>'tree_view_manager'));
					break;
				}
			}
		}

		if (array_keys($tree) != $saved_ids) {
			// Need to reorder based on sibling heirarchy changes!
			$count = count($saved_ids) - 1;
			for ($i = $count; $i >= 0; $i--) {
				$ret = $this->Category->moveUp($saved_ids[$i], true);
				// Returns false when we move an already-at-top to the top, so ignore falses.
			}
		}

		$this->Session->setFlash('Структурата е запаметена успешно');
		$this->redirect(array('admin' => true, 'plugin' => null, 'controller' => 'categories', 'action'=>'tree_view_manager'), null, true);
	}
	
	function admin_reorder() {
		$this->Category->id = null;
		
		$this->Category->recover('parent');
	}
	
}
?>